import { DeleteOutlined } from '@ant-design/icons'
import { withId, withoutId } from '@gnlab/utils'
import { Button } from 'antd'
import { EditModal, Empty } from '@/desktop/components'
import { PreviewWord } from '@/desktop/components/words'
import type { Word, Words } from '@/services/resources/words-library'
import './index.module.less'

export default function SendConfirm(props: {
  words: Words | null
  send: (words: Words) => void
  onCancel: () => void
}) {
  const { words, send, onCancel } = props

  return <EditModal title="发送话术" width="750px" open={words !== null} onCancel={onCancel}>
    {words !== null ? <Content words={words} send={send} onCancel={onCancel} /> : null}
  </EditModal>
}

function Content(props: { words: Words; send: (words: Words) => void; onCancel: () => void }) {
  const { words, send, onCancel } = props

  // 带上 id 以避免用数组 index 作为 key
  // 可保证删除某个 item 时，其他 item 不会因为 index 变化强制重新渲染（例如图片会重新加载）
  const [items, setItems] = useState(() => withId(words.items))

  const removeItem = useCallback(
    (id: number) => {
      const updated = [...items].filter(v => v.id !== id)
      setItems(updated)
    },
    [items],
  )

  const updateItem = useCallback(
    (id: number, word: Word) => {
      const updated = [...items]
      const index = updated.findIndex(v => v.id === id)
      updated[index] = { id, ...word }
      setItems(updated)
    },
    [items],
  )

  const sendUpdated = useCallback(
    () => send({ ...words, items: withoutId(items) }),
    [send, words, items],
  )

  return <>
    <main styleName="content">
      {items.map(word => {
        return <div key={word.id} styleName="item-wrap">
          <DeleteOutlined styleName="remove" onClick={() => removeItem(word.id)} />
          <PreviewWord word={word} onUpdate={(updated: Word) => updateItem(word.id, updated)} />
        </div>
      })}

      {!items.length ? <Empty description="没有可发送的内容" /> : null}
    </main>

    <footer>
      <Button onClick={onCancel}>取消</Button>
      <Button disabled={!items.length} type="primary" onClick={sendUpdated}>
        发送
      </Button>
    </footer>
  </>
}
